package com.kai.base.fragment

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.viewbinding.ViewBinding
import com.kai.base.base.basic.model.BaseModel
import com.kai.base.base.basic.model.ErrorState
import com.kai.base.base.basic.model.LoadState
import com.kai.base.base.basic.model.SuccessState
import com.kai.base.utils.AppUtils
import com.kai.base.utils.ClassUtil

/**
 * @Author: 小强同学
 * @Date:  2021/1/19 10:39
 * @Description:  java类作用描述
 */
abstract class BaseMvFragment<VM : BaseModel, VB : ViewBinding> : BaseFragment<VB>() {

    protected var mViewModel: VM? = null

    override fun initViews() {
        initViewModel()
        initViewModelAction()
        super.initViews()
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val viewModelClass = ClassUtil.getViewModel<VM>(this)
        if (viewModelClass != null) {
            mViewModel = ViewModelProvider.AndroidViewModelFactory(AppUtils.getApplication())
                .create(viewModelClass)
        }
    }

    private fun initViewModelAction() {
        mViewModel?.let { baseViewModel ->
            baseViewModel.mStateLiveData.observe(this, Observer { stateActionState ->
                when (stateActionState) {
                    LoadState -> showLoading()
                    SuccessState -> {
                        showContent()
                        loadFinish()
                    }
                    is ErrorState -> {
                        showError()
                        loadFinish()
                        stateActionState.message?.apply { showToast(this) }
                    }
                }
            })
        }
    }

    /**
     * 数据加载完成 成功/失败
     */
    open fun loadFinish() {}

}